#include "Protocol.hpp"
#include "Socket.hpp"

#include <string>
#include <iostream>
#include <memory>
#include <unistd.h>
#include <ctime>

int main(int argc, char* argv[])
{
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    //链接套接字
    Socket* s = new TcpSocket();
    if(!s->BuildConnectSocket(serverip, serverport))
    {
        std::cout << "sockfd: " << s->GetSockfd() << " connect " << serverip << ":" << serverport << " failed" << std::endl;
        return 0;
    }
    else std::cout << "sockfd: " << s->GetSockfd() << " connect " << serverip << ":" << serverport << " success" << std::endl;
    
    std::unique_ptr<Factory> factory = std::make_unique<Factory>();

    srand(time(nullptr));
    const std::string opers = "+-*/%";
    while(true)
    {
        //创建出Request对象，为了发送
        int x = rand() % 100;
        usleep(rand() % 123);
        int y = rand() % 100;
        usleep(rand() % 123);
        char op = opers[rand() % opers.size()];
        std::shared_ptr<Request> req = factory->BuildRequest(x, y, op);

        //将它序列化
        std::string request_message;
        req->Serialize(&request_message);
        // std::cout << request_message << std::endl;    // DEBUG
        //保留下算式
        std::string test_req = request_message;
        //再添加报头
        request_message = EnCode(request_message);
        //开始发送
        s->Send(request_message);

        std::string response_package;
        
        if(!s->Recv(&response_package, 1024)) continue;
        std::string message_recv;
        if(!DeCode(response_package, &message_recv)) continue;
        std::shared_ptr<Response> resp = factory->BuildResponse();
        resp->DeSerialize(message_recv); 

        std::cout << test_req << " = "<< resp->GetResult() << " [" << resp->GetCode() << "]" << std::endl;
        sleep(1);
    }
    s->CloseSockfd();
}